package Lock;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;

import java.util.concurrent.TimeUnit;

/**
 * @author create on 2021/7/12
 * 使用锁操作资源
 * http://ifeve.com/zookeeper-lock/
 */
public class ExampleClientThatLocks {


    /**
     * 锁
     */
    private final InterProcessMutex lock;

    /**
     * 共享资源
     */
    private final FakeLimitResource resource;

    /**
     * 客户端
     */
    private final String clientName;

    public ExampleClientThatLocks(CuratorFramework client, String lockPath, FakeLimitResource resource, String clientName) {
        this.resource = resource;
        this.clientName = clientName;
        lock = new InterProcessMutex(client, lockPath);
    }

    public void doWork (long time , TimeUnit timeUnit) throws  Exception{
        if (!lock.acquire(time, timeUnit)){
            throw new IllegalStateException(clientName + " could not acquire the lock");
        }

        try {
            System.out.println(clientName + "has the lock");
            //使用资源
            resource.use();
        }catch (Exception e){
            System.out.println(clientName + "releaseing the lock");
            lock.release();

        }
    }

}
